#include "mywidget.h"
#include "ui_mywidget.h"
#include <QDebug>
#include <QKeyEvent>
#include <QMessageBox>
#include <QEvent>


MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyWidget)
{
    ui->setupUi(this);

    //单位毫秒
    int timer_id = this->startTimer(1000);
    //停止定时器
//    this->killTimer(timer_id);

    connect(ui->pushButton,&MyButton::pressed,
            [=]()
            {
                qDebug()<<"clicked被按下";
            }
            );

    //安装过滤器
    ui->label_2->installEventFilter(this);
    ui->label_2->setMouseTracking(true);

}

MyWidget::~MyWidget()
{
    delete ui;
}

void MyWidget::keyPressEvent(QKeyEvent *event)
{
    qDebug()<<event->key();
    if(event->key() == Qt::Key_A)
    {
       qDebug()<<"keyA";
    }
}

void MyWidget::timerEvent(QTimerEvent *event)
{
    static int sec = 0;
    sec++;
    ui->label->setText(QString("%1").arg(sec));

//    if(event->timerId() == timer_id)
    //    判断是哪个定时器
}

void MyWidget::mousePressEvent(QMouseEvent *event)
{
    qDebug()<<"++++++++";
}

void MyWidget::closeEvent(QCloseEvent *event)
{
    int ret = QMessageBox::question(this,"question","是否需要关闭窗口");
    if(ret == QMessageBox::Yes)
    {
        //关闭窗口
        //接收后数据不会传递
        event->accept();
    }
    else
    {
        //不关闭敞口
        //忽略事件 传递给父组件
        event->ignore();
    }
}

bool MyWidget::event(QEvent *event)
{
    //返回true 说明事件已经被处理
//    switch (event->type()) {
//    case QEvent::Close:
//        closeEvent(event);
//        break;
//    case QEvent::MouseMove:
//        mouseMoveEvent(event);
//        break;

//        //...

//    default:
//        break;
//    }
    if(event->type() == QEvent::Timer)
    {
        //QTimerEvent *event
        //QTimerEvent *e = static_cast<QTimerEvent *>(event);
        //timerEvent(e);
        return true;//干掉定时器
    }
    else if(event->type() == QEvent::KeyPress)
    {
        QKeyEvent * e = static_cast<QKeyEvent *>(event);

        if(e->key()== Qt::Key_B)
        {
            qDebug()<<"B被按下";
            return QWidget::event(event); // 只有按下B  才转发
        }
        //return QWidget::event(event);;  AB都有效
        return true; // 只有B有效

    }
    else
    {
        return QWidget::event(event);
    }

}

//过滤器 创建  重写虚函数（ 只是创建过滤器  没有安装  在构造函数里安装）
bool MyWidget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->label_2)
    {
        //判断事件
        if(event->type() == QEvent::MouseMove)
        {
            QMouseEvent * e = (QMouseEvent *)(event);
//          QMouseEvent * e = dynamic_cast<QMouseEvent *>(event);
//          QMouseEvent * e = static_cast<QMouseEvent *>(event);
            ui->label_2->setText(QString("mouse move(%1,%2)").arg(e->x()).arg(e->y()));
            return true;
        }
        else
        {
            //养成习惯
            return QWidget::eventFilter(watched,event);
        }
    }
    else
    {
        return QWidget::eventFilter(watched,event);
    }

}
